<template>
  <div class="app-container">
    <el-row :gutter="10">
      <el-col :span="3">
        <el-input
          size="small"
          placeholder="输入关键字进行过滤"
          v-model="filterText" clearable
        >
        </el-input>
        <el-tree
          class="filter-tree"
          :data="orgOptions"
          node-key="id"
          :props="defaultProps"
          :expand-on-click-node="false"
          default-expand-all
          :filter-node-method="filterNode"
          ref="origationTree"
          @node-click="handleNodeClick"
        >
        </el-tree>
      </el-col>

      <el-col :span="21">
        <el-form
        class="searchForm" :inline="true" size="mini"
          ref="searchForm"
          :model="searchForm"  label-width="65px"
        >
          <el-form-item label="姓名">
            <el-input v-model="searchForm.name" clearable placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="searchForm.phone" clearable placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item label="角色">
            <el-select clearable
              v-model="searchForm.roleIds"
              multiple
              placeholder="请选择角色"
            >
              <el-option
                v-for="item in roleOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-search"
              @click="doSearch"
              >搜索</el-button
            >
            <el-button
              type="default"
              size="mini"
              icon="el-icon-refresh"
              @click="resetSearch"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
        <div class="searchs-content">
          <el-button
            v-permission="['system:user:add']"
            type="primary"
            size="mini"
            plain
            icon="el-icon-plus"
            @click="addDialog"
            >新增</el-button
          >
        </div>
        <Table
          :tableHeader="tableHeader"
          :tableData="tableData"
          :tableLoading="listLoading"
        >
        <template slot="isEnable" slot-scope="scope">
        <el-switch
          v-permission="['system:user:isEnable']"
          v-model="scope.row.isEnable"
          :active-value="'1'"
          :inactive-value="'0'"
          @change="isCancelEnable($event, scope.row)"
        >
        </el-switch>
      </template>
          <template
            slot="action"
            slot-scope="scope"
            v-if="scope.row.id != 1 && scope.row.id != userInfo.id"
          >
            <el-button
              type="primary"
              size="mini"
              @click="addDialog(scope.row)"
              v-permission="['system:user:edit']"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              @click="deleteRow(scope.row)"
              v-permission="['system:user:remove']"
              >删除</el-button
            >
            <el-button
              v-if="scope.row.type != 'P'"
              type="success"
              size="mini"
              @click="permissionSet(scope.row)"
              v-permission="['system:user:dataauth']"
              >权限分配</el-button
            >
          </template>
        </Table>
        <pagination
          v-if="total > 0"
          :total="total"
          :page.sync="searchForm.pageNum"
          :limit.sync="searchForm.pageSize"
          @pagination="fetchData"
        />
      </el-col>
    </el-row>

    <!-- 弹框 -->
    <Dialog
      :visible="visible"
      width="35%"
      :isFooter="false"
      :title="dialogTitle + '人员'"
      @cancelDialog="cancelDialog"
    >
      <AddUser :visible="visible"
        :organizationId="organizationId"
        :orgType="currentOrganization.type"
        :userForm="dialogForm"
        :options="roleOptions"
        :orgOptions="orgOptions"
        @cancelDialog="cancelDialog"
      ></AddUser>
    </Dialog>

    <!-- 权限分配 -->
    <Dialog
      :visible="perVisible"
      width="35%"
      title="权限分配"
      @confirmDialog="perConfirmDialog"
      @cancelDialog="perCancelDialog"
    >
      <div class="clear-permission-btn">
        <el-button
          type="warning"
          size="mini"
          @click="isResetPermission"
          v-if="currentRole == '200'"
          >权限重置</el-button
        >
      </div>
      <el-form
        ref="perDialogForm"
        :model="perDialogForm"
        label-width="120px"
        :rules="perDialogRules" size="small"
      >
        <el-form-item label="设备类型">
          <el-select clearable
            v-model="perDialogForm.model"
            multiple
            placeholder="请选择设备类型"
          >
            <el-option
              v-for="item in equipTypeOption"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="运营商">
          <el-select clearable
            v-model="perDialogForm.operator"
            multiple
            placeholder="请选择运营商"
          >
            <el-option
              v-for="item in operatorOption"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="地区" class="area-select" prop="city">
          <el-cascader clearable 
            :options="areaSelectData"
            :props="areaSelectDataProps"
            ref="areaSelectRef"
            :show-all-levels="false"
            v-model="perDialogForm.city" :collapse-tags="true"
            :placeholder="areaCheckList.length==0 ?'请选择省市区':''"
            @change="areaChange"
          >
        </el-cascader>
        <el-tooltip effect="dark" placement="top">
          <div slot="content" style="white-space: pre-line;max-width: 480px;">{{ areaCheckList.join(',') }}</div>
         <span @click="toggleCascader">{{ areaCheckList.join(',') }}</span>
        </el-tooltip>
        </el-form-item>
      </el-form>
    </Dialog>
  </div>
</template>

<script>
import { userManage, roleManage, authority } from "@/api/system";
import { factuerManage, operator, equipType, region } from "@/api/factuer";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import Table from "@/components/Table";
import Dialog from "@/components/Dialog";
import AddUser from "./addUser.vue";

import { handleConfirm } from "@/utils/messageBox";

import { removeNullUndefined, filterTreeData } from "@/utils/index.js";
import { mapState } from "vuex";
export default {
  name: "User",
  components: { Pagination, Table, Dialog, AddUser },

  watch: {
    filterText(val) {
      this.$refs.origationTree.filter(val);
    },
  },
  data() {
    return {
      listLoading: false,
      total: 0,
      searchForm: {
        pageNum: 1,
        pageSize: 15,
        name: "",
        phone: "",
        roleIds: [],
      },
      organizationId: "",

      tableHeader: [
        {
          type: "index",
          label: "序号",
          width: "60",
          fixed: true,
        },
        {
          label: "登录名",
          prop: "loginName",
        },
        {
          label: "手机号",
          prop: "phone",
        },
        {
          label: "姓名",
          prop: "userName",
        },
        {
          label: "角色",
          prop: "roleNames",
        },

        {
          label: "组织",
          prop: "organizationName",
        },
        { slot: "isEnable", label: "启用状态" },
        { slot: "action", label: "操作", width: "260" },
      ],
      tableData: [],
      visible: false, //弹框标识
      dialogForm: {
        userName: "",
        loginName: "",
        password: "",
        phone: "",
        roleIds: [],
        organizationId: "",
      },
      dialogTitle: "",
      orgOptions: [],
      roleOptions: [],

      perVisible: false,
      perDialogForm: {
        operator: [],
        model: [],
        city: [],
      },
      perDialogRules: {
        name: [{ required: true, message: "请输入", trigger: "blur" }],
      },
      areaSelectData: [],
      areaSelectDataProps: {
        multiple: true,
        // checkStrictly: true,
        multipleLimit: 3,
        children: "childrens",
        value: "code",
        label: "name",
        emitPath: false,
      },
      filterText: "",
      areaCheckList:[],//选中的省市区

      defaultProps: {
        children: "children",
        label: "name",
      },
      equipTypeOption: [],
      operatorOption: [],
      currentRole: null,
      currentUser: {},
      currentOrganization: {}, //当前点击组织
    };
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
  },
  created() {
    this.getFactuerList();
    if (this.roleOptions.length == 0) {
      this.getRoleList();
    }
  },
  methods: {
    // 获取所属组织机构
    getFactuerList() {
      factuerManage("/all", "post", {}, 1)
        .then((res) => {
          let datas = res.data;
          this.orgOptions = datas;
          let curOrgId = datas.length > 0 ? datas[0].id : "";
          this.organizationId = curOrgId;
          this.currentOrganization = datas.length > 0 ? datas[0] : {};
          this.$nextTick(() => {
            this.$refs.origationTree.setCurrentKey(curOrgId); //data[0].id为默认选中的节点
          });
          this.fetchData();
        })
        .catch((err) => {});
    },
    // 角色list
    getRoleList() {
      roleManage("/allow/bind/list", "get", {}, 1)
        .then((res) => {
          this.roleOptions = res.data;
        })
        .catch((err) => {});
    },
    // 地区list
    async getRegionList() {
      let datas = await region("/tree");
      this.areaSelectData = filterTreeData(datas.data);
    },
    fetchData(val) {
      this.searchForm.pageNum = val ? val.page : this.searchForm.pageNum;

      this.listLoading = true;
      this.tableData = [];
      this.total = 0;
      userManage("/list",'post', {
        ...removeNullUndefined(this.searchForm),
        organizationId: this.organizationId,
      })
        .then((res) => {
          this.tableData = res.data;
          this.total = +res.total;

          this.searchForm.pageNum = +res.pageNum;
        })
        .finally(() => {
          this.listLoading = false;
        });
    },
    // 弹框取消
    cancelDialog(type) {
      this.visible = false;
      this.dialogForm = {
        userName: "",
        loginName: "",
        password: "",
        phone: "",
        roleIds: [],
        organizationId: "",
      };
      if (type) this.fetchData();
    },

    perCancelDialog() {
      this.perVisible = false;
      this.areaCheckList=[];
      this.resetDialogForm("perDialogForm");
    },
    // 弹框确认
    perConfirmDialog() {
      let { operator, model, city } = this.perDialogForm;
      let isSubmit =
        operator.length != 0 || model.length != 0 || city.length != 0;
      if (!isSubmit) {
        return this.$message.error("设备类型、运营商、地区至少选1个");
      } else {
        handleConfirm("确定要给该用户分配权限吗？", "warning", "提示")
          .then((res) => {
            this.setPermission();
          })
          .catch((err) => {});
      }
    },
    permissionSet(row) {
      this.perVisible = true;
      if (this.operatorOption.length == 0) {
        this.getOperatorList();
      }

      if (this.areaSelectData.length == 0) {
        this.getRegionList();
      }
      if (this.equipTypeOption.length == 0) {
        this.getEquipTypeList();
      }
      this.perDialogForm = {
        operator: [],
        model: [],
        city: [],
      };
      this.currentRole = null;
      this.currentUser = row;
      authority(`/select/${row.id}`)
        .then((res) => {
          // !res.data,表示没有任何权限，走新增接口；否则走编辑接口；
          // R：地区；O：运营商;ET:设备类型
          let datas = res.data;
          this.currentRole =
            datas &&
            datas.authorityEntities &&
            datas.authorityEntities.length > 0
              ? "200"
              : null;
          if (datas) {
            let O = datas.authorityEntities.filter((item) => item.type == "O");
            this.perDialogForm.operator = O.length > 0 ? O[0].value : [];
            let R = datas.authorityEntities.filter((item) => item.type == "R");
            this.perDialogForm.city = R.length > 0 ? R[0].value : [];
            let ET = datas.authorityEntities.filter(
              (item) => item.type == "ET"
            );
            this.perDialogForm.model = ET.length > 0 ? ET[0].value : [];
            setTimeout(()=>{
              this.areaChange();
            },300);
          }
        })
        .catch((err) => {
          this.currentRole = null;
        });
    },
    async getOperatorList() {
      this.operatorOption = [];
      let datas = await operator("/all", "get", {
        organizationId: this.organizationId,
      });
      this.operatorOption = datas.data;
    },
    async getEquipTypeList() {
      let datas = await equipType("/datails", "post");
      this.equipTypeOption = datas.data;
    },
    // 新增
    addDialog(row) {
      this.visible = true;
      this.dialogForm = {
        userName: "",
        loginName: "",
        password: "123456",
        phone: "",
        roleIds: [],
        organizationId: this.organizationId,
      };
      if (row.id) {
        this.dialogTitle = "编辑";
        let {
          userName,
          loginName,
          password,
          phone,
          roleIds,
          id,
          organizationId,
        } = { ...row };
        userName = userName ? userName : "";
        loginName = loginName ? loginName : "";
        password = password ? password : "";
        phone = phone ? phone : "";
        roleIds = roleIds ? roleIds : [];
        organizationId = organizationId ? organizationId : "";
        this.dialogForm = {
          userName,
          loginName,
          password,
          phone,
          roleIds,
          id,
          organizationId,
        };
      } else {
        this.dialogTitle = "新增";
      }
    },
    submitDialogForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
        } else {
          return false;
        }
      });
    },
    resetDialogForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 权限分配
    setPermission() {
      let param = {
        authorityEntities: [],
        userId: this.currentUser.id,
      };
      // R：地区；O：运营商;ET:设备类型
      if (this.perDialogForm.operator.length > 0) {
        param.authorityEntities.push({
          authorityType: "O",
          type: "O",
          value: this.perDialogForm.operator,
        });
      }
      if (this.perDialogForm.model.length > 0) {
        param.authorityEntities.push({
          authorityType: "ET",
          type: "ET",
          value: this.perDialogForm.model,
        });
      }
      if (this.perDialogForm.city.length > 0) {
        param.authorityEntities.push({
          authorityType: "R",
          type: "R",
          value: this.perDialogForm.city,
        });
      }
      let url = this.currentRole == "200" ? "/update" : "/insert";

      //编辑
      authority(url, JSON.stringify(param)).then((res) => {
        if (res.code == 200) {
          this.$message.success(res.message);
          this.perVisible = false;
        }
      });
    },
    // 删除
    deleteRow(row) {
      //确认弹窗
      handleConfirm("删除后不可恢复，确定执行此操作吗？", "warning", "提示")
        .then((res) => {
          this.doDelete(row);
        })
        .catch((err) => {
          // do something cancel
        });
    },
    doDelete(row) {
      userManage(`/update/${row.id}`)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success(res.message);
            this.fetchData();
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    isCancelEnable(e, row) {
      if (e == '1') {
        row.isEnable = '0';
      } else {
        row.isEnable = '1';
      }
      handleConfirm(
        `确定要${row.isEnable == 1 ? "禁用" : "启用"}吗？`,
        "warning",
        "提示"
      )
        .then((res) => {
          this.doCancelEnable(row);
        })
        .catch((err) => {});
    },
    // 禁用/启用
    doCancelEnable(row) {
      let url =row.isEnable ==1?'/disable/':"/enable/";
      userManage(
        `${url}${row.id}`,
        "PUT",
        {},
        1
      ).then((res) => {
        if (res.code == 200) {
          this.$message.success(res.message);
          this.fetchData();
        }
      });
    },

    areaChange(e) {
      let checkedlist = this.$refs.areaSelectRef.getCheckedNodes();

      // 如果三级全选就显示二级的，没有全选就显示三级的
      checkedlist = checkedlist.filter(option => !(option.parent && option.parent.checked))
      let citiesList = []
      for (let i = 0; i < checkedlist.length; i++) {
        citiesList.push(checkedlist[i])
      }
      this.areaCheckList = []
      for (let i = 0; i < citiesList.length; i++) {
        this.areaCheckList.push(citiesList[i].label)
      }
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    handleNodeClick(e) {
      this.currentOrganization = e;
      this.organizationId = e.id;
      this.fetchData();
      this.operatorOption = [];
    },
    isResetPermission() {
      handleConfirm("确定要重置该用户权限吗？", "warning", "提示")
        .then((res) => {
          this.doResetPermission();
        })
        .catch((err) => {});
    },
    doResetPermission() {
      authority(`/delete/${this.currentUser.id}`).then((res) => {
        if (res.code == 200) {
          this.$message.success(res.message);
          this.perVisible = false;
        }
      });
    },
    // 搜索重置
    resetSearch() {
      this.searchForm = {
        pageNum: this.searchForm.pageNum,
        pageSize: this.searchForm.pageSize,
        name: "",
        phone: "",
        roleIds: [],
      };
    },
    doSearch() {
      this.searchForm.pageNum = 1;
      this.fetchData();
    },
    toggleCascader(){
      this.$refs.areaSelectRef.toggleDropDownVisible();
    },
  },
};
</script>
<style lang="scss">
.el-tree-node.is-current > .el-tree-node__content {
  color: #fff;
  background: #5473e8;
}

.el-tree-node {
  margin-top: 8px;
}
</style>
<style lang="scss" scoped>
@import "@/styles/common.scss";
.searchForm {
    .el-form-item {
        margin-bottom: 8px;
    }
}
.filter-tree {
  max-height: 86vh;
  overflow: auto;
  margin-top: 12px;
  border-right: 1px solid #efefef;
}

.el-select,
.el-cascader {
  width: 94%;
}

.clear-permission-btn {
  margin: -10px 0 20px 0;
}
.area-select{
  position: relative;
  span{
    position: absolute;
    left: 12px;
    top: 0;
    width: 80%;
    color: #909399;
    @include exceedFlow(1);
    cursor: pointer;
  }
  ::v-deep .el-tag{
    display: none;
  }
  ::v-deep .el-cascader__tags{
    // z-index: 99;
    // height: 40px;
    // cursor: pointer;
  }
}
</style>
